package com.ylq.reggie_take_away.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylq.reggie_take_away.common.CustomException;
import com.ylq.reggie_take_away.dto.SetMealDto;
import com.ylq.reggie_take_away.entity.SetMeal;
import com.ylq.reggie_take_away.entity.SetMealDish;
import com.ylq.reggie_take_away.mapper.SetMealMapper;
import com.ylq.reggie_take_away.service.SetMealDishService;
import com.ylq.reggie_take_away.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal> implements SetMealService {

    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetMealDto setMealDto) {
        //保存套餐基本信息setmeal,insert操作
        this.save(setMealDto);

        List<SetMealDish> setMealDishes = setMealDto.getSetMealDishes();
        List<SetMealDish> collect = setMealDishes.stream().map((item) -> {
            item.setSetmealId(setMealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //保存套餐和菜品的关联信息setmeal_dish
        setMealDishService.saveBatch(collect);
    }

    /**
     * 删除套餐，同时删除套餐和菜品的关联数据
     *
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，停售的可以删除
        //select count(*) from setMeal where id in (1,2,3) and status = 1;
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetMeal::getId, ids);
        queryWrapper.eq(SetMeal::getStatus, 1);
        int count = this.count(queryWrapper);
        //不能删除，抛出异常
        if (count>0){
            throw new CustomException("套餐正在售卖中,不能删除");
        }

        //可以删除,先删除套餐表中数据
        this.removeByIds(ids);
        /*
        删除关系表中数据
        delete from set_meal_dish where set_meal_id in (1,2,3);
        */
        LambdaQueryWrapper<SetMealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetMealDish::getSetmealId, ids);
        setMealDishService.remove(lambdaQueryWrapper);
    }

    @Override
    public void updateStatus(SetMeal setMeal) {
        this.updateById(setMeal);
    }
}
